'use strict';

const HttpManager = require('./manager/HttpManager');
const BaseService = require('../../libs/base/BaseService');
const sysconfig = require('../../config/sysconfig');
const Code = require('../../config/code');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const axios = require('axios'); // 添加axios用于发送GET请求

/**
 * http跟gateway 服务是外部信息进入的两个进程。
 */
class WTHttp extends BaseService {
  /**
   * 构造函数
   */
  constructor() {
    super('Http');
    console.log(`[BaseHttp] 构造函数 isDebug=${this.isDebug}`);
    this.app = express();
    this.port = 7001;
    this.workName = sysconfig.playerWork.FOOD
  }

  async init() {
    // 配置CORS - 允许跨域访问
    this.app.use(cors({
      origin: '*', // 允许所有来源访问，生产环境应该限制为特定域名
      credentials: true, // 如果使用 Cookie，需要设置为 true
      methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
      allowedHeaders: ['Content-Type', 'Authorization']
    }));

    // 配置中间件
    this.app.use(bodyParser.json());
    this.app.use(bodyParser.urlencoded({ extended: true }));

    // 设置路由
    this.setupRoutes();

    // 启动服务器
    this.app.listen(this.port, () => {
      console.log(`[BaseHttp] HTTP服务已启动，监听端口: ${this.port}`);
    });

    console.log(`[BaseHttp] 服务初始化完成`);
  }


  /**
   * 设置API路由
   */
  setupRoutes() {
    // 微信登录接口        
    this.app.post('/wxLogin', async (req, res) => {
      try {
        //查看是否有数据，如果没有则添加新用户，如果前端有存pid，则直接使用pid数据登陆
        const { code, wxres, pid, sessionId, platform } = req.body;
        const ip = req.ip;
        let getFlag = true, result, openid, session_key, player;
        //如果pid session同时存在，而且sessionId在时间范围内，则直接使用
        if (pid && sessionId) {
          let info = HttpManager.getByPid(pid, sessionId);
          if (info && info.code == Code.SUCCESS) {
            getFlag = false;
            //检查用户数据是否存在，如果不存在，则注册用户
            result = await MySQL.loginByPid(pid);
          }
        }
        if (getFlag) {
          // 对微信接口发起GET请求
          // const response = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
          //   params: {
          //     appid: 'wx3f5768fa8110299e', // 替换为你的appid
          //     secret: '8c65c4ad3216171a0cd42c5b1e9efb01', // 替换为你的appsecret
          //     js_code: code,
          //     grant_type: 'authorization_code'
          //   }
          // });

          // 处理微信接口返回的数据
          // const { openid, session_key } = response.data;
          openid = 'oOxdf7P3uI5RagglZ2Vy70gj86-U';
          if (!openid) {
            return res.status(500).json({ success: false, data: '微信登录失败' });
          }
          //检查用户数据是否存在，如果不存在，则注册用户
          result = await MySQL.loginByPlatformId(openid, platform);
        }
        if (result.code == 0) {
          let info = result.data;
          info.ip = ip;
          //用户存在，用数据库的信息来登陆
          player = await Globalhall.playerLogin(info);
        } else {
          //用微信的数据来登陆
          let info = wxres.userInfo;
          info.openid = openid;
          info.platform = platform;
          info.ip = ip;
          player = await Globalhall.playerRegedit(info);
        }
        player.platform = platform;
        const hplayer = HttpManager.setOne(player);
        //通知hall,玩家成功登陆
        await RPC.Hall.PlayerManager.loginPlayer(hplayer.port, this.workName, player);
        // 在这里可以添加更多的业务逻辑，比如保存session_key等
        res.json({
          success: true,
          data: {
            pid: player.pid,
            token: hplayer.token
          }
        });
      } catch (error) {
        console.error('[BaseHttp] 微信登录请求处理错误:', error);
        res.status(500).json({ success: false, data: '服务器错误' });
      }
    });

    // 获取食物接口
    this.app.post('/getFood', async (req, res) => {
      try {
        const info = HttpManager.getByPid(req.body.pid, req.body.token);
        if (info.code) {
          console.log('token过期');
          res.status(500).json({ success: false, data: 'token过期' });
        }
        const playerInfo = await RPC.Hall.PlayerManager.getFood(info.data.port, info.data.pid, req.body.taboo || '', req.body.change);
        // 在这里处理获取食物的逻辑
        res.json({
          success: true,
          data: {
            foods: playerInfo
          }
        });
      } catch (error) {
        console.error('[WTHttp] 获取食物请求处理错误:', error);
        res.status(500).json({ success: false, data: '服务器错误' });
      }
    });

    // 获取食物接口
    this.app.post('/setLocation', async (req, res) => {
      try {
        const info = HttpManager.getByPid(req.body.pid, req.body.token);
        if (info.code != Code.SUCCESS) {
          console.log('token过期');
          res.status(500).json({ success: false, data: 'token过期' });
        }
        RPC.Hall.PlayerManager.setLocation(info.data.port, info.data.pid, req.body.latitude, req.body.longitude);
        // 在这里处理获取食物的逻辑
        res.json({
          success: true,
          data: "地理位置更新成功"
        });
      } catch (error) {
        console.error('[WTHttp] 获取食物请求处理错误:', error);
        res.status(500).json({ success: false, data: '服务器错误' });
      }
    });

    console.log('[WTHttp] 路由设置完成');
  }
}

module.exports = WTHttp;